'''
Created on May 11, 2012

@author: Dan Baskette
'''

'''
TODO
1) Modify Add,etc so that it creates Node objects



'''
from BaseMenu import BaseMenu
from Node import Node
import os
import time
import socket

class HadoopNodeMenu(BaseMenu):
    
    nodes=[]
    Nodes = []
  
 
 #  THIS SECTION IMPLEMENTSA PING TO CHECK HOST VALIDITY       
#        ping = "".join(os.popen("ping -c1 "+choice).readlines())
#        if re.search("64 bytes from",ping):
#            print "\nSuccess. Host Added."
#            self.nodes.append(choice)
#        else:
#            print "\nNo Host Found.  Please check Host Information."
 
 
 
    def __AddNode(self):
        
        os.system("clear")        
        nodeName = "x"

        
        print "------------------------------------------------"
        print "             ADD NODES TO CONFIGURATION"
        print "------------------------------------------------"
        print " !!** Press Enter on blank line when done  **!!!"
        print "------------------------------------------------"
        print "        Available Personality Profiles "
        print "------------------------------------------------"
        print "         n  ->  Namenode"
        print "         s  ->  Secondary Namenode"
        #print "         b  ->  Backup Namenode"
        print "         j  ->  JobTracker"
        print "         d  ->  Datanode / TaskTracker"
        print "------------------------------------------------\n"


        while nodeName <> "":
            found=0
            personalities = ""
            nodeName=raw_input("Enter a Node Name: ")
            if nodeName <> "":
                if len(self.Nodes) > 0:
                    for node in self.Nodes:
                        if nodeName == node.hostName:
                            print "Node name Already exists. Please Try Again."
                            found = 1 
                if found==0:
                    while personalities == "":
                        personalities = raw_input("Enter 1 or more Personalities (ex njd): ")
                    ipAddress = socket.gethostbyname(nodeName)        
                    node = Node(nodeName,ipAddress, personalities)    
                    self.Nodes.append(node)  
                  
                      
    def __ExpandNodeTypes(self,nodeChars):
        personalities = ""
       

        for char in nodeChars:
            if char == 'n':
                personalities = personalities + ":" +"Namenode"
            elif char == 's':
                personalities = personalities + ":" +"Secondary Namenode"
            elif char == 'b':
                personalities = personalities + ":" +"Backup Namenode"
            elif char == 'j':
                personalities = personalities + ":" +"JobTracker"
            elif char == 'd':
                personalities = personalities + ":" +"Datanode:TaskTracker"
        return personalities[1:]
        
        
        
        
    def __ListNodes(self):
        print"\nNodes in Cluster"
        print"-------------------------"


        for node in self.Nodes:
            print node.hostName + " | " + node.ipAddress + " | "+self.__ExpandNodeTypes(node.personalities)
        print"-------------------------"
        print
        raw_input("\n Press Enter to Continue.")

    def __RemoveNode(self):
        nodeFound = 0
        print"-------------------------"
        for node in self.Nodes:
            print node.hostName + " | " + self.__ExpandNodeTypes(node.personalities)
        print"-------------------------"
        nodeName = raw_input("\nEnter Name of Node to remove from cluster: ")
        for node in self.Nodes:
            if (node.hostName == nodeName):
                print "\nNode Removed"
                raw_input("\n Press Enter to Continue.")
                nodeFound = 1
                print node
                self.Nodes.remove(node)
               
        if nodeFound == 0:
            print "\nNode Not Found"
            raw_input("\n Press Enter to Continue.")
 
 
 
    def __SaveNodeList(self):
        hadoopNodesFile = open("./conf/setup/hadoopNodes.conf", "w")
        for node in self.nodes:
            hadoopNodesFile.write(node['nodeName']+","+node['personality'] + "\n")
        hadoopNodesFile.close()
   
        
        
    def __ConfigurePersonalities(self):
        choice = "\n Node Personality Configuration\n"
        personalities={}
        while choice <> "":
            personalities['Namenode']=raw_input("Namenode: ")
            personalities['Secondary Namenode']=raw_input("Secondary Namenode: ")
            personalities['Backup Namenode']=raw_input("Backup Namenode: ")
            personalities['JobTracker']=raw_input("JobTracker: ")
            
            
            
            
        print personalities
        
        
        

    def BuildHadoopNodeMenu(self):
        hdnChoice =  -1
        menuItems = ["Add Nodes","Remove Nodes","List Nodes","Save and Return to Main Menu"]
        menuOptions = {1 : self.__AddNode,2 : self.__RemoveNode,3 : self.__ListNodes}
        while (hdnChoice < 0):
            try:
                hdnChoice = BaseMenu.BuildMenu(self,"GPHD Install - Node Membership",menuItems,menuOptions)        
            except:
                hdnChoice = -1 
        
        if (int(hdnChoice) > 0):
           menuOptions[int(hdnChoice)]() 
        else:
            self.__SaveNodeList()
            return hdnChoice





    def __init__(self,Nodes):
        BaseMenu.__init__(self)
        self.Nodes = Nodes
      